using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace PegasCompany.Data
{
	[DataObject]
	[Serializable]
	public partial class AccessRole
	{
		#region Constants

		private const string TableName = "[dbo].[AccessRole]";

		#endregion

		#region Properties

		public int? RoleId { get; set; }
		public string Name { get; set; }
		public string Description { get; set; }
		public bool? IsDeleted { get; set; }
		public DateTime? CreateDate { get; set; }
		public DateTime? LastModifiedDate { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("RoleId", typeof(Int32));
			ds.Tables[TableName].Columns.Add("Name", typeof(String));
			ds.Tables[TableName].Columns.Add("Description", typeof(String));
			ds.Tables[TableName].Columns.Add("IsDeleted", typeof(Boolean));
			ds.Tables[TableName].Columns.Add("CreateDate", typeof(DateTime));
			ds.Tables[TableName].Columns.Add("LastModifiedDate", typeof(DateTime));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["RoleId"] = RoleId ?? (object) DBNull.Value;
			dr["Name"] = Name ?? (object) DBNull.Value;
			dr["Description"] = Description ?? (object) DBNull.Value;
			dr["IsDeleted"] = IsDeleted ?? (object) DBNull.Value;
			dr["CreateDate"] = CreateDate ?? (object) DBNull.Value;
			dr["LastModifiedDate"] = LastModifiedDate ?? (object) DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			RoleId = dr["RoleId"] != DBNull.Value ? Convert.ToInt32(dr["RoleId"]) : RoleId = null;
			Name = dr["Name"] != DBNull.Value ? Convert.ToString(dr["Name"]) : Name = null;
			Description = dr["Description"] != DBNull.Value ? Convert.ToString(dr["Description"]) : Description = null;
			IsDeleted = dr["IsDeleted"] != DBNull.Value ? Convert.ToBoolean(dr["IsDeleted"]) : IsDeleted = null;
			CreateDate = dr["CreateDate"] != DBNull.Value ? Convert.ToDateTime(dr["CreateDate"]) : CreateDate = null;
			LastModifiedDate = dr["LastModifiedDate"] != DBNull.Value ? Convert.ToDateTime(dr["LastModifiedDate"]) : LastModifiedDate = null;
		}

		public static List<AccessRole> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<AccessRole> objects = new List<AccessRole>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");

            if (ds.Tables[TableName] == null)
                throw new ApplicationException("Cannot find table [dbo].[AccessRole] in DataSet.");

			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				AccessRole instance = new AccessRole();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			return objects;
		}

		#endregion

		#region CRUD Methods

		public static AccessRole Get(Int32 roleId)
		{
			AccessRole instance = new AccessRole();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspAccessRole_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, roleId))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0) throw new ApplicationException(String.Format("Could not get AccessRole ID:{0} from Database.", roleId));
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(String name, String description, Boolean? isDeleted, DateTime? createDate, DateTime? lastModifiedDate, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspAccessRole_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, name, description, isDeleted, createDate, lastModifiedDate))
			{
				RoleId = Convert.ToInt32(transaction == null ? db.ExecuteScalar(dbCommand) : db.ExecuteScalar(dbCommand, transaction));
			}
		}

		/// <summary>
		/// Insert current AccessRole to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(Name, Description, IsDeleted, CreateDate, LastModifiedDate, transaction);
		}

		#endregion

		#region UPDATE

		private static void Update(Int32? roleId, String name, String description, Boolean? isDeleted, DateTime? createDate, DateTime? lastModifiedDate, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspAccessRole_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@roleId"].Value = roleId;
				dbCommand.Parameters["@name"].Value = name;
				dbCommand.Parameters["@description"].Value = description;
				dbCommand.Parameters["@isDeleted"].Value = isDeleted;
				dbCommand.Parameters["@createDate"].Value = createDate;
				dbCommand.Parameters["@lastModifiedDate"].Value = lastModifiedDate;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		private static void Update(Int32? roleId, String name, String description, Boolean? isDeleted, DateTime? createDate, DateTime? lastModifiedDate)
		{
			Update(roleId, name, description, isDeleted, createDate, lastModifiedDate, null);
		}

		private static void Update(AccessRole accessRole)
		{
			accessRole.Update();
		}

		private static void Update(AccessRole accessRole, DbTransaction transaction)
		{
			accessRole.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Update(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspAccessRole_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@roleId"].SourceColumn = "RoleId";
				dbCommand.Parameters["@name"].SourceColumn = "Name";
				dbCommand.Parameters["@description"].SourceColumn = "Description";
				dbCommand.Parameters["@isDeleted"].SourceColumn = "IsDeleted";
				dbCommand.Parameters["@createDate"].SourceColumn = "CreateDate";
				dbCommand.Parameters["@lastModifiedDate"].SourceColumn = "LastModifiedDate";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();
			
					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		private void Update()
		{
			Update((DbTransaction)null);
		}

		#endregion

		#region DELETE

		public static void Delete(Int32? roleId, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspAccessRole_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, roleId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		public static void Delete(Int32? roleId)
		{
			Delete(roleId, null);
		}

		/// <summary>
		/// Delete current AccessRole from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		public void Delete(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspAccessRole_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, RoleId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
			RoleId = null;
		}

		/// <summary>
		/// Delete current AccessRole from database.
		/// </summary>
		public void Delete()
		{
			Delete((DbTransaction)null);
		}

		#endregion

		#region SEARCH

		private static List<AccessRole> Search(Int32? roleId = null, String name = null, String description = null, Boolean? isDeleted = null, DateTime? createDate = null, DateTime? lastModifiedDate = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspAccessRole_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, roleId, name, description, isDeleted, createDate, lastModifiedDate))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}

		private static List<AccessRole> Search(AccessRole searchObject)
		{
			return Search(searchObject.RoleId, searchObject.Name, searchObject.Description, searchObject.IsDeleted, searchObject.CreateDate, searchObject.LastModifiedDate);
		}

		#endregion

		#endregion

		#endregion
	}
}